import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Resizable } from 'react-resizable';
import {
  Button,
  Card,
  Input,
  Table,
  Divider,
  Form,
  Select,
  Row,
  Col,
  Switch,
  Tag,
  Popconfirm,
  message,
  Icon,
} from 'antd';
import { debug } from 'util';
import moment from 'moment';
import styles from './Menu.less';
import request from '@/utils/request';
import { stringify } from 'qs';
import router from 'umi/router';
import MenuModal from './MenuModal';

const FormItem = Form.Item;
const Option = Select.Option;
const ResizeableTitle = (props) => {
  const { onResize, width, ...restProps } = props;

  if (!width) {
    return <th {...restProps} />;
  }

  return (
    <Resizable width={width} height={0} onResize={onResize}>
      <th {...restProps} />
    </Resizable>
  );
};

@connect(({ PagesModel, ComboModule }) => ({ PagesModel, ComboModule }))
@Form.create()
class Menu extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      queryForm: {
        status: '',
        queryProperties: ''
      },
      dataSource: [],
      loading: false,
      menuModal: {
        visible: false,
        isEdit: undefined,
        menuId: undefined
      }
    };
    const {
      PagesModel,
      location: { pathname },
    } = props;
    if (pathname in PagesModel) {
      const { queryForm, pageInfo } = PagesModel[pathname];
      this.state.queryForm = queryForm;
      this.state.pageInfo = pageInfo;
    }
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'ComboModule/sys' });

    this.refreshTable();
  }

  refreshTable = opts => {
    const { dispatch } = this.props;

    const paramTarget = {
      ...this.state,
      loading: true,
      ...opts,
    };
    this.setState({
      loading: true,
      ...opts,
    });

    const params = {
      no_level: true,
    };
    request(`/api/sys/menu/queryAll?${stringify(params)}`).then(root => {
      if (!root.success) {
        this.setState({ loading: false, });
        message.error(root.msg);
        return;
      }

      this.setState({
        dataSource: root.data,
        loading: false,
      });

      //保存当前状态
      const {
        PagesModel,
        location: { pathname },
      } = this.props;
      const { queryForm, pageInfo } = paramTarget;
      PagesModel[pathname] = { queryForm, pageInfo };
    });
  };

  handleTableChange = (pagination, filters, sorter) => {
    const { queryForm } = this.state;
    const { status } = filters;
    if (status) {
      queryForm.status = status.join(',');
    }
  };

  handleSearch = (e) => {
    if (e) e.preventDefault();
    const { form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      this.setState({ queryForm: fieldsValue });
    });
  };

  handleReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch();
  };

  handleAdd = () => {
    //router.push({
    //  pathname: '/admin/system/menu/dialog',
    //  query: {
    //    isEdit: false,
    //    menuId: '',
    //  },
    //});
    this.setState({
      menuModal: {
        visible: true,
        isEdit: false,
        menuId: ''
      }
    })
  };

  handleEdit = record => {
    router.push({
      pathname: '/admin/system/menu/dialog',
      query: {
        isEdit: true,
        menuId: record.menuId,
      },
    });
  };

  handleEnable = (record, actived) => {
    this.setState({ loading: true });
    const formData = new FormData();
    formData.append('menuId', record.menuId);
    formData.append('status', actived);

    request(`/api/sys/menu/updateStatus`, {
      method: 'POST',
      body: formData,
    }).then(root => {
      if (root.success) {
        message.success('操作成功');
        this.refreshTable({});
        return;
      }
      message.error(root.msg);
      this.setState({ loading: false });
    });
  };

  renderForm = () => {
    const { getFieldDecorator } = this.props.form;
    const { queryForm: { status, queryProperties } } = this.state;

    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="检索条件">
              {getFieldDecorator('queryProperties', {
                initialValue: queryProperties
              })(<Input placeholder="菜单名称/功能URL/备注" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="启用状态">
              {
                getFieldDecorator('status', {
                  initialValue: status,
                })(
                  <Select placeholder="请选择" style={{ width: '100%' }} >
                    <Option value="">全部</Option>
                    <Option value="1">启用中</Option>
                    <Option value="-1">已停用</Option>
                  </Select>
                )
              }
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  handleResize = index => (e, { size }) => {
    this.setState(({ columns }) => {
      const nextColumns = [...columns];
      nextColumns[index] = {
        ...nextColumns[index],
        width: size.width,
      };
      return { columns: nextColumns };
    });
  };

  components = {
    header: {
      cell: ResizeableTitle,
    },
  };

  render() {
    const {
      dataSource,
      loading,
      queryForm: { status, queryProperties },
      menuModal
    } = this.state;
    const { queryForm } = this.state;
    const { ComboModule } = this.props;

    const dict = {};
    const root = { children: [] };

    const hasCondition = (queryProperties.length > 0 ? 1 : 0);
    // 第一次迭代，构建字典和 matched 属性
    dataSource.forEach(v => {
      dict[v.menuId] = { ...v };
      const node = dict[v.menuId];

      if (hasCondition > 0) {
        if (v.menuUrl.toString().toLowerCase().includes(queryProperties.toLowerCase()) ||
          v.menuName.toString().toLowerCase().includes(queryProperties.toLowerCase()) ||
          v.remark.toString().toLowerCase().includes(queryProperties.toLowerCase())) {
          //命中
          node.matched = true;
          node.childMatched = true;
        } else {
          //没有命中
          node.matched = false;
        }
      } else {
        //没有条件，直接判命中
        node.matched = true;
      }
    });

    // 第二次迭代，构建树形结构 和父类的 matched 属性
    Object.keys(dict).forEach(menuId => {
      const node = dict[menuId];
      if (node.treeUp && node.treeUp != '' && node.treeUp != '0') {
        if (node.treeUp in dict) {
          node.parent = dict[node.treeUp];
          if (node.matched) {
            let me = node;
            while (me != null) {
              me.matched = true;
              me = me.parent;
            }
          }
          if (typeof node.parent.children === 'undefined') {
            node.parent.children = [node];
          } else {
            node.parent.children.push(node);
          }
        }
      } else {
        node.parent = null;
        root.children.push(node);
      }
    });

    // 第三次迭代，剔除所有没有 matched 属性的节点
    if (hasCondition > 0) {
      const ft = parent => {
        if (typeof parent.children === 'undefined') {
          return;
        }
        parent.children = parent.children.filter(
          ({ matched, childMatched }) => matched || childMatched
        );
        if (parent.children.length == 0) {
          delete parent.children;
          return;
        }
        for (let i = 0; i < parent.children.length; i++) {
          if (parent.children[i].matched && !parent.children[i].childMatched) {
            ft(parent.children[i]);
          }
        }
      };
      ft(root);
    }

    const ResizeableTitle = (props) => {
      const { onResize, width, ...restProps } = props;

      if (!width) {
        return <th {...restProps} />;
      }

      return (
        <Resizable width={width} height={0} onResize={onResize}>
          <th {...restProps} />
        </Resizable>
      );
    };

    const columns = [
      {
        title: '菜单名称',
        dataIndex: 'menuName',
        width: 320,
        render: (val, record) => {
          return (
            <Fragment>
              {' '}
              <i className={record.menuIcon} style={{ marginRight: 10 }} />
              {val}
            </Fragment>
          );
        },
      },
      {
        title: '操作',
        key: 'action',
        width: 120,
        render: (text, record) => {
          const action = [];
          action.push(<Icon type="edit" title="编辑" onClick={() => this.handleEdit(record)} />);
          action.push(<Icon type="plus" title="添加下级" onClick={() => this.handleAdd(record)} />);
          action.push(<Divider type="vertical" />)
          action.push(<Icon type="arrow-up" title="上移" />)
          action.push(<Icon type="arrow-down" title="下移" />)
          return <Fragment>{action}</Fragment>;
        },
      },
      { title: '功能URL', dataIndex: 'menuUrl', },
      {
        title: '启用状态',
        dataIndex: 'status',
        width: 100,
        render: (val, record) => {
          if (val === '1') {
            return (
              <Popconfirm
                placement="topLeft"
                title="确认禁用？"
                onConfirm={() => this.handleEnable(record, '-1')}
                okText="禁用"
                cancelText="取消">
                <Switch checkedChildren="启用中" unCheckedChildren="已禁用" checked={true} />
              </Popconfirm>
            )
          }

          return (
            <Popconfirm
              placement="topLeft"
              title="确认启用？"
              onConfirm={() => this.handleEnable(record, '1')}
              okText="启用"
              cancelText="取消">
              <Switch checkedChildren="启用中" unCheckedChildren="已禁用" checked={false} />
            </Popconfirm>
          )
        },
      },
      {
        title: '平台',
        dataIndex: 'sysName',
        width: 180,
        filterMultiple: false,
        filtered: status != null && status != '',
        filteredValue: status != null && status != '' ? [status] : null,
        filters: ComboModule.sys
          ? ComboModule.sys.map(v => {
            return { value: v.sys_id, text: v.sys_name };
          })
          : [],
      },
      { title: '备注', dataIndex: 'remark', width: 300 },
      {
        title: '更新时间',
        dataIndex: 'timeUpdate',
        width: 150,
        sorter: true,
        render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
      },
    ]
    .map((col, index) => ({
      ...col,
      onHeaderCell: column => ({
        width: column.width,
        onResize: this.handleResize(index),
      }),
    }));

    return (
      <Fragment>
        <Card>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleAdd()}>
                新建根级
            </Button>
            </div>
            <Table
              bordered
              size="small"
              components={this.components}
              scroll={{ x: 1280 }}
              columns={columns}
              loading={loading}
              pagination={false}
              dataSource={root.children}
              onChange={this.handleTableChange}
              rowKey="menuId"
            />
          </div>
        </Card>
        <MenuModal {...menuModal}
          handleCancel={this.menuModalCancel}
          handleOk={this.menuModalOk} />
      </Fragment>
    );
  }

  menuModalCancel = () => {
    const { menuModal } = this.state
    this.setState({
      menuModal: {
        ...menuModal,
        visible: false
      }
    })
  }

  menuModalOk = () => {

  }
}

export default Menu;
